package cn.dancepeak.interceptor;

import cn.dancepeak.service.impl.LoginServiceImplImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component //交给spring容器
public class MyLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginServiceImplImpl loginServiceImpl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前请求是否是已经登录的人在操作
        //1.从请求中获取前端传来的token串
        String token = request.getHeader("token");
        //2.如果token为空 去登录
        if("null".equals(token)){
            PrintWriter writer = response.getWriter();
            //没有登录 去登录
            writer.write("{\"code\":\"401\",\"success\":false}");
            return false;//阻止拦截器继续下去
        }
        //3.如果token不为空，判断是否登录失效
        if(!loginServiceImpl.getMap().containsKey(token)){
            PrintWriter writer = response.getWriter();
            //4.没有登录 去登录
            writer.write("{\"code\":\"401\",\"success\":false}");
            return false;//阻止拦截器继续下去
        }
        //5.否则，放行
        return true;
    }
}
